from urllib.parse import urlencode,parse_qs
from urllib.request import urlopen
import json

class QQNetworkError(Exception):
    pass
class OAuthQQ:

    def __init__(self,app_id,app_key,redirect_uri,state="/"):

        self.app_id = app_id
        self.app_key = app_key
        self.redirect_uri = redirect_uri
        self.state = state

    def url(self):

        query = {
            "response_type":"code",
            "client_id":self.app_id,
            "redirect_uri":self.redirect_uri,
            "state":self.state
        }
        query_string = urlencode(query)

        return "https://graph.qq.com/oauth2.0/authorize?"+query_string

    def access_token(self,code):

        query_dict = {
            "grant_type": "authorization_code",
            "client_id": self.app_id,
            "client_secret": self.app_key,
            "code": code,
            "redirect_uri": self.redirect_uri,
        }
        query_string = urlencode(query_dict)
        url = "https://graph.qq.com/oauth2.0/token?" + query_string
        result = urlopen(url)
        content_string = result.read().decode()
        content_dict = parse_qs(content_string)
        print(content_dict["access_token"][0])
        return content_dict["access_token"][0]

    def open_id(self,token):

        query_dict = {
            "access_token": token,
            "fmt": "json",
        }
        query_string = urlencode(query_dict)
        url = "https://graph.qq.com/oauth2.0/me?" + query_string
        try:
            result = urlopen(url)
            content_string = result.read().decode()
            content_dict = json.loads(content_string)
        except:
            raise QQNetworkError

        return content_dict["openid"]